package com.my.redisson.delayqueue;

import com.my.redisson.domain.DelayEvent;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DelayQueueProvider {

    @Value("delay_queue_call")
    private String group;
    @Autowired
    private RedissonClient redissonClient;

    public void addDelayEvent(DelayEvent event) {
        RBlockingQueue<DelayEvent> blockingFairQueue = redissonClient.getBlockingQueue(group);
        RDelayedQueue<DelayEvent> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        delayedQueue.offer(event, event.getDelayTime(), TimeUnit.MILLISECONDS);
        log.info("provider addDelayEvent finish group:{} event:{}", group, event);
    }

    public void removeDelayEvent(DelayEvent event) {
        RBlockingQueue<DelayEvent> blockingFairQueue = redissonClient.getBlockingQueue(group);
        RDelayedQueue<DelayEvent> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        //event序列化之后和队列中保存的event一致才能成功删除
        //boolean suc = delayedQueue.remove(event);
        boolean suc = false;
        //迭代器删除
        Iterator<DelayEvent> it = delayedQueue.iterator();
        while (it.hasNext()) {
            DelayEvent delayEvent = it.next();
            if (Objects.equals(event, delayEvent)) {
                it.remove();
                suc = true;
                break;
            }
        }
        log.info("provider removeDelayEvent finish group:{} event:{} success:{}", group, event, suc);
    }

    public Collection<DelayEvent> getDelayEventList() {
        RBlockingQueue<DelayEvent> blockingFairQueue = redissonClient.getBlockingQueue(group);
        RDelayedQueue<DelayEvent> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
        return delayedQueue;
    }

}
